<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="模型编号" prop="modelNo">
        <el-input
          v-model="queryParams.modelNo"
          placeholder="请输入模型编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型状态" prop="modelStateName">
        <el-select
          v-model="queryParams.modelStateName"
          placeholder="请选择模型状态"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in modelStateOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成分名称" prop="constituentName">
        <el-input
          v-model="queryParams.constituentName"
          placeholder="请输入成分名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器编号" prop="instrumentNo">
        <el-input
          v-model="queryParams.instrumentNo"
          placeholder="请输入仪器编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器名称" prop="instrumentName">
        <el-input
          v-model="queryParams.instrumentName"
          placeholder="请输入仪器名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建模人" prop="trainerName">
        <el-input
          v-model="queryParams.trainerName"
          placeholder="请输入建模人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采样时间" prop="samplingTime">
        <el-date-picker
          clearable
          v-model="queryParams.samplingTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采样时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="isRowVisible">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:data:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['model:data:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['model:data:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['model:data:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      ref="modelTable"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="模型编号"
        width="138"
        align="center"
        prop="modelNo"
      />
      <el-table-column label="成分名称" align="center" prop="constituentName" />
      <el-table-column label="部门名称" align="center" prop="departmentName" />
      <el-table-column
        label="仪器编号"
        width="138"
        align="center"
        prop="instrumentNo"
      />
      <el-table-column label="仪器名称" align="center" prop="instrumentName" />
      <el-table-column
        label="采样时间"
        align="center"
        prop="samplingTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.samplingTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="建模数据编号" align="center" prop="constructNo" />
      <el-table-column label="模型状态" align="center" prop="modelStateName">
        <template slot-scope="scope">
          <el-tag :type="getTagType(scope.row.modelStateName)">
            {{ scope.row.modelStateName }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        width="130"
        align="center"
        class-name="small-padding fixed-width"
        v-if="isRowVisible"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['model:data:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['model:data:remove']"
            >删除</el-button
          >
          <el-button
            v-if="scope.row.modelStateName === '暂存'"
            size="mini"
            type="text"
            @click="handleTrain(scope.row)"
            v-hasPermi="['model:data:remove']"
            >手动训练</el-button
          >
          <el-button
            v-if="scope.row.modelStateName === '暂存'"
            size="mini"
            type="text"
            @click="handleAutoTraining(scope.row)"
            v-hasPermi="['model:data:remove']"
            >一键训练</el-button
          >
          <el-button
            v-else-if="scope.row.modelStateName === '已完成'"
            size="mini"
            type="text"
            class="detail-btn"
            @click="handleDetail(scope.row)"
            v-hasPermi="['model:data:remove']"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模型对话框 -->
    <el-drawer
      id="dataFormDrawer"
      :title="title"
      :visible.sync="open"
      size="400px"
      style="height: 100vh"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="模型编号" prop="modelNo">
          <el-input
            v-model="form.modelNo"
            disabled
            placeholder="请输入模型编号"
          />
        </el-form-item>
        <!-- <el-form-item label="建模数据编号" prop="constructNo">
          <el-input
            v-model="form.constructNo"
            placeholder="请输入建模数据编号"
          />
        </el-form-item> -->
        <el-form-item label="成分名称" prop="constituentName">
          <el-input
            readonly
            v-model="form.constituentName"
            placeholder="请选择成分名称"
            @click.native="constituentDialogVisible = true"
            @input="$refs.form.validateField('constituentName')"
            class="pointer-input"
          >
            <i slot="suffix" class="el-icon-search el-input__icon"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-select
            v-model="form.departmentName"
            size="small"
            placeholder="请选择部门"
            clearable
          >
            <el-option
              v-for="item in options.departments"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仪器编号" prop="instrumentNo">
          <el-input
            readonly
            v-model="form.instrumentNo"
            placeholder="请选择仪器编号"
            @click.native="instrumentDialogVisible = true"
            class="pointer-input"
          >
            <!-- 添加选择图标 -->
            <i slot="suffix" class="el-icon-search el-input__icon"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="仪器名称" prop="instrumentName">
          <el-input
            v-model="form.instrumentName"
            placeholder="请输入仪器名称"
            disabled
          />
        </el-form-item>
        <el-form-item label="建模人" prop="trainerName">
          <el-input v-model="form.trainerName" placeholder="请输入建模人" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div
        class="drawer-footer"
        style="
          position: absolute;
          bottom: 0;
          width: 100%;
          padding: 16px;
          text-align: right;
        "
      >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-drawer>

    <el-dialog
      title="选择仪器编号"
      :visible.sync="instrumentDialogVisible"
      width="80%"
    >
      <instrument-data
        ref="instrumentDataRef"
        :is-row-visible="false"
        @selection-change="handleRowSelection"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseInstrument">确 定</el-button>
        <el-button @click="instrumentDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择成分名称对话框 -->
    <el-dialog
      title="选择成分名称"
      :visible.sync="constituentDialogVisible"
      width="80%"
    >
      <constituent-data
        ref="constituentDataRef"
        :is-row-visible="false"
        @selection-change="handleConstituentSelection"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseConstituent">确 定</el-button>
        <el-button @click="constituentDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listData,
  getData,
  delData,
  addData,
  updateData,
} from "@/api/model/data";
import { listDept } from "@/api/system/dept";
import { listData as listConstituent } from "@/api/constituent/data";
import { listData as listInstrument } from "@/api/instrument/data";
import InstrumentData from "@/views/instrument/data/index.vue";
import ConstituentData from "@/views/constituent/data/index.vue";

export default {
  name: "Data",
  dicts: ["model_state"],
  props: {
    isRowVisible: {
      type: Boolean,
      default: true,
    },
    // 获取已完成状态的数据
    getFinishedData: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    InstrumentData,
    ConstituentData,
  },
  data() {
    return {
      constituentDialogVisible: false,
      selectedInstrumentData: null, // 选中的仪器数据
      instrumentDialogVisible: false,
      options: {},
      // 模型状态选项（静态写死）
      modelStateOptions: [
        { value: "暂存", label: "暂存" },
        { value: "已完成", label: "已完成" },
      ],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模型表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelNo: null,
        constructId: null,
        constructNo: null,
        constituentId: null,
        constituentName: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        samplingTime: null,
        trainerId: null,
        trainerName: null,
        maxPotential: null,
        cvRatioCode: null,
        cvRatioName: null,
        preMethodCode: null,
        preMethodName: null,
        waveSelectMethodCode: null,
        waveSelectMethodName: null,
        rc2: null,
        rmsecv: null,
        rp2: null,
        rmsep: null,
        rpd: null,
        tTest: null,
        rsd: null,
        modelStateCode: null,
        modelStateName: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // modelNo: [
        //   { required: true, message: "模型编号不能为空", trigger: "blur" },
        // ],
        constructId: [
          { required: true, message: "建模数据id不能为空", trigger: "blur" },
        ],
        constructNo: [
          { required: true, message: "建模数据编号不能为空", trigger: "blur" },
        ],
        constituentId: [
          { required: true, message: "成分id不能为空", trigger: "blur" },
        ],
        constituentName: [
          { required: true, message: "成分名称不能为空", trigger: "blur" },
        ],
        departmentName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "部门id不能为空", trigger: "blur" },
        ],
        instrumentId: [
          { required: true, message: "仪器id不能为空", trigger: "blur" },
        ],
        instrumentNo: [{ required: true, message: "仪器编号不能为空" }],
        instrumentName: [
          { required: true, message: "仪器名称不能为空", trigger: "blur" },
        ],
        samplingTime: [
          { required: true, message: "采样时间不能为空", trigger: "blur" },
        ],
        // trainerId: [
        //   { required: true, message: "建模人id不能为空", trigger: "blur" },
        // ],
        // trainerName: [
        //   { required: true, message: "建模人不能为空", trigger: "blur" },
        // ],
        modelStateCode: [
          {
            required: true,
            message: "模型状态代码不能为空",
            trigger: "change",
          },
        ],
        modelStateName: [
          { required: true, message: "模型状态不能为空", trigger: "blur" },
        ],
        isDelete: [
          { required: true, message: "是否删除不能为空", trigger: "blur" },
        ],
        creatorId: [
          { required: true, message: "新增人id不能为空", trigger: "blur" },
        ],
        creator: [
          { required: true, message: "新增人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "新增时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    if (this.getFinishedData) {
      this.queryParams.modelStateName = "已完成";
    }
    this.getList();
    this.getDepartments();
  },
  methods: {
    handleConstituentSelection(selection) {
      // 限制只能选择一个成分
      const tableRef = this.$refs.constituentDataRef.$refs.constituentTable;
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1];
        this.$nextTick(() => {
          tableRef.clearSelection(); // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true); // 仅保留当前选中
        });
        this.selectedConstituentData = lastSelected;
      } else {
        this.selectedConstituentData = selection[0] || null;
      }
      console.log("查看选中的成分数据", this.selectedConstituentData);
    },
    chooseConstituent() {
      const selectedConstituent = this.selectedConstituentData;
      if (selectedConstituent) {
        this.$set(
          this.form,
          "constituentId",
          selectedConstituent.constituentId
        );
        this.$set(
          this.form,
          "constituentName",
          selectedConstituent.constituentName
        );

        // 手动清除验证错误
        this.$nextTick(() => {
          this.$refs.form.clearValidate(["constituentId", "constituentName"]);
        });

        this.constituentDialogVisible = false; // 关闭对话框
      } else {
        this.$modal.msgError("请先选择一个成分");
      }
    },
    chooseInstrument() {
      const selectedInstrument = this.selectedInstrumentData;
      if (selectedInstrument) {
        this.form.instrumentId = selectedInstrument.instrumentId;
        this.form.instrumentNo = selectedInstrument.instrumentNo;
        this.form.instrumentName = selectedInstrument.instrumentName;
        this.instrumentDialogVisible = false; // 关闭对话框
      } else {
        this.$modal.msgError("请先选择一个仪器");
      }
    },
    handleRowSelection(selection) {
      const tableRef = this.$refs.instrumentDataRef.$refs.instrumentTable;
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1];
        this.$nextTick(() => {
          tableRef.clearSelection(); // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true); // 仅保留当前选中
        });
        this.selectedInstrumentData = lastSelected;
      } else {
        this.selectedInstrumentData = selection[0] || null;
      }
      console.log("查看选中的仪器数据", this.selectedInstrumentData);
    },
    getTagType(state) {
      const map = {
        暂存: "danger",
        已完成: "success",
        // 审核中: "warning",
      };
      return map[state] || "info";
    },
    handleTrain(row) {
      this.reset();
      this.$router.push({
        path: "/model/data/train",
        query: {
          modelNo: row.modelNo,
          modelId: row.modelId,
        },
      });
    },
    handleAutoTraining(row) {
      this.reset();
      this.$router.push({
        path: "/model/data/autoTrain",
        query: {
          modelNo: row.modelNo,
          modelId: row.modelId,
        },
      });
    },
    handleDetail(row) {
      this.reset();
      this.$router.push({
        path: "/model/data/detail",
        query: {
          modelNo: row.modelNo,
          modelId: row.modelId,
        },
      });
    },
    async setConstituentInfo() {
      try {
        const response = await listConstituent({
          constituentName: this.form.constituentName,
        });

        if (
          response.code !== 200 ||
          !response.rows ||
          response.rows.length === 0
        ) {
          this.$modal.msgError("成分名称不存在");
          return;
        }
        this.$set(this.form, "constituentId", response.rows[0].constituentId);
        this.form.constituentName = response.rows[0].constituentName;
        console.log("成分名称ID", this.form.constituentId);
      } catch (error) {
        console.error("查询成分名称失败:", error);
        this.$modal.msgError("查询成分失败");
      }
    },
    async setInstrumentInfo() {
      try {
        const response = await listInstrument({
          instrumentName: this.form.instrumentName,
          instrumentNo: this.form.instrumentNo,
        });

        if (response.code === 200 && response.rows?.length > 0) {
          this.form.instrumentId = response.rows[0].instrumentId;
          console.log("仪器信息", response.rows[0]);
        } else {
          this.$modal.msgError("仪器信息不存在");
          throw new Error("仪器信息不存在");
        }
      } catch (error) {
        console.error("查询仪器失败:", error);
        this.$modal.msgError("查询仪器失败");
        throw error; // 向上传递错误，阻止后续流程
      }
    },
    async getDepartments() {
      try {
        const response = await listDept(); // 替换为实际的部门列表API
        this.options.departments = response.data;
        console.log("获取部门列表成功:", response.data);
      } catch (error) {
        console.error("获取部门列表失败:", error);
      }
    },
    /** 查询模型列表 */
    getList() {
      this.loading = true;
      this.queryParams.constructStateName = "已完成"
      listData(this.queryParams).then((response) => {
        // 按创建时间倒序排列，最新的数据在前面
        this.dataList = response.rows.sort((a, b) => {
          // 如果有创建时间字段，则按创建时间倒序排列
          if (a.createTime && b.createTime) {
            return new Date(b.createTime) - new Date(a.createTime);
          }
          // 如果没有创建时间字段，按模型ID倒序排列（假设ID越大越新）
          return b.modelId - a.modelId;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: null,
        modelNo: null,
        constructId: null,
        constructNo: null,
        constituentId: null,
        constituentName: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        samplingTime: null,
        trainerId: null,
        trainerName: null,
        maxPotential: null,
        cvRatioCode: null,
        cvRatioName: null,
        preMethodCode: null,
        preMethodName: null,
        waveSelectMethodCode: null,
        waveSelectMethodName: null,
        rc2: null,
        rmsecv: null,
        rp2: null,
        rmsep: null,
        rpd: null,
        tTest: null,
        rsd: null,
        modelStateCode: null,
        modelStateName: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        createTime: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.modelId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.$emit("selection-change", selection);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modelId = row.modelId || this.ids;
      getData(modelId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模型";
      });
    },
    /** 提交按钮 */
    async submitForm() {
      try {
        const valid = await new Promise((resolve, reject) => {
          this.$refs["form"].validate((valid) => {
            if (valid) resolve(true);
            else reject(new Error("表单验证失败"));
          });
        });

        if (this.form.modelId != null) {
          // 更新
          updateData(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
          });
        } else {
          await this.setConstituentInfo();
          await this.setInstrumentInfo();

          // 填入部门id
          const dept = this.options.departments.find(
            (dept) => dept.deptName === this.form.departmentName
          );
          if (dept) {
            this.form.departmentId = dept.deptId;
          } else {
            this.$modal.msgError("部门不存在");
            return;
          }

          this.form.modelStateName = "暂存";
          this.form.modelStateCode = "01";

          addData(this.form).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
        this.open = false;
        this.getList();
      } catch (error) {
        console.error("提交失败", error);
        this.$modal.msgError(error.message || "提交失败");
      }
      // this.$refs["form"].validate((valid) => {
      //   if (valid) {
      //     if (this.form.modelId != null) {
      //       updateData(this.form).then((response) => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       this.setConstituentInfo();
      //       addData(this.form).then((response) => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$modal
        .confirm('是否确认删除模型编号为"' + modelIds + '"的数据项？')
        .then(function () {
          return delData(modelIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "model/data/export",
        {
          ...this.queryParams,
        },
        `data_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
#dataFormDrawer .el-input {
  width: 85%; /* 输入框占满剩余宽度（匹配图片效果） */
}

.detail-btn {
  color: #67c23a; /* 绿色 */
}
</style>
